package com.forlove.app.qselect.friend.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.StringUtil;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.QRCodeAsync;
import com.forlove.app.qselect.answer.widght.InviteFriendDialog;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.AddNewFriendPresenter;
import com.forlove.app.qselect.friend.view.AddNewFriendView;
import com.forlove.app.qselect.friend.widget.dialog.ShowQRCodeDialog;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.umeng.socialize.UMShareAPI;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * 扫一扫添加好友
 * Created by yjl on 2017/10/15.
 */

public class AddNewFriendActivity extends BaseActivity implements View.OnClickListener,
        LoaderManager.LoaderCallbacks<Bitmap>, AddNewFriendView {
    @BindView(R.id.view_fade_back)
    FrameLayout view_fade_back;

    @BindView(R.id.view_search_account)
    RelativeLayout view_search_account;

    @BindView(R.id.bt_invite_friend)
    AppCompatTextView bt_invite_friend;

    @BindView(R.id.image_mine_qrcode)
    ImageView image_mine_qrcode;

    @BindView(R.id.view_qr_code)
    LinearLayout view_qr_code;

    @BindView(R.id.view_scan)
    LinearLayout view_scan;

    @BindView(R.id.text_mine_name)
    TextView text_mine_name;

    @BindView(R.id.text_add_phone_friend)
    AppCompatTextView text_add_phone_friend;
    private QRCodeAsync qrCodeAsync;
    private InviteFriendDialog inviteFriendDialog;
    private UserEntity userEntity;
    private ShowQRCodeDialog showQRCodeDialog;
    private AddNewFriendPresenter addNerFriendPresenter;
    private IntentIntegrator intentIntegrator;
    private Bitmap QRCodeBitmap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_new_friend;
    }

    /**
     * 跳转扫描
     */
    public void customScan() {
        if (intentIntegrator == null) {
            intentIntegrator = new IntentIntegrator(this);
        }
        intentIntegrator.setOrientationLocked(false)
                .setCaptureActivity(ScanQRCodeActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描
    }

    @Override
    public void initView() {
        addNerFriendPresenter = new AddNewFriendPresenter(this);
        view_fade_back.setOnClickListener(this);
        view_search_account.setOnClickListener(this);
        inviteFriendDialog = new InviteFriendDialog(this, null, null, null);
        bt_invite_friend.setOnClickListener(this);
        view_qr_code.setOnClickListener(this);
        view_scan.setOnClickListener(this);
        text_add_phone_friend.setOnClickListener(this);
        if (UserManager.getUserLoginState(this)) {
            userEntity = UserManager.getUesrInfo(this);
            if (!TextUtils.isEmpty(userEntity.userName)) {
                text_mine_name.setText(userEntity.userName);
            } else {
                text_mine_name.setText("未设置用户名");
            }
        } else {
            startActivity(new Intent(this, ChoiceNewAgeActivity.class));
            this.finish();
        }

        getSupportLoaderManager().restartLoader(QRCodeAsync.ASYNC_ID, null, this);

    }


    private QRCodeAsync createQrcodeAnsy() {
        if (qrCodeAsync == null && userEntity != null) {

            qrCodeAsync = new QRCodeAsync(this);
        }
        return qrCodeAsync;
    }

    private void requestSearchFriend(String mobile) {
        if (TextUtils.isEmpty(mobile) || !StringUtil.isPhone(mobile)) {
            Toast.makeText(this, "没有找到该好友!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map param = new HashMap();
        param.put("mobile", mobile);
        addNerFriendPresenter.loadSearchFriend(param);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_fade_back:
                onBackPressed();
                break;
            case R.id.view_search_account:
                startActivity(new Intent(this, SearchFriendActivity.class));
                break;
            case R.id.bt_invite_friend:
                if (!inviteFriendDialog.isShowing()) {
                    inviteFriendDialog.show();
                }
                break;
            case R.id.view_qr_code:

                if (showQRCodeDialog != null) {
                    showQRCodeDialog.show();
                }
                break;
            case R.id.view_scan:
                customScan();
                break;
            case R.id.text_add_phone_friend:
                //跳转添加手机联系人
                startActivity(new Intent(this, AddContactsFriendActivity.class));
                break;
        }
    }

    @Override
    public Loader<Bitmap> onCreateLoader(int id, Bundle args) {
        return createQrcodeAnsy();
    }

    @Override
    public void onLoadFinished(Loader<Bitmap> loader, Bitmap data) {
        getSupportLoaderManager().destroyLoader(QRCodeAsync.ASYNC_ID);
        QRCodeBitmap = data;
        image_mine_qrcode.setImageBitmap(QRCodeBitmap);
//        qrcodeBitmap = data;
        if (showQRCodeDialog == null && QRCodeBitmap != null) {
            showQRCodeDialog = new ShowQRCodeDialog(this, QRCodeBitmap);
        }
    }

    @Override
    public void onLoaderReset(Loader<Bitmap> loader) {

    }

    @Override
    // 通过 onActivityResult的方法获取 扫描回来的 值
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(this, "扫描失败!", Toast.LENGTH_LONG).show();
            } else {
//                Toast.makeText(this, "扫描成功", Toast.LENGTH_LONG).show();
                // ScanResult 为 获取到的字符串
                String ScanResult = intentResult.getContents();
                LogUtil.e("yjl", "扫描结果:" + ScanResult);
                requestSearchFriend(ScanResult);

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    @Override
    public void showScanViewData(SearchFriendEntity searchFriendEntity) {
        if (searchFriendEntity != null && !searchFriendEntity.isFriend) {
            Intent intent = new Intent(this, SearchUserInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("friendinfo", searchFriendEntity);
            bundle.putString("mobile", searchFriendEntity.friendEntity.getAvaliableMobile());
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            //TODO 跳转好友详情页
            Toast.makeText(this, "此人已经是好友了", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MineInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("mobile", searchFriendEntity.friendEntity.mobile);
            intent.putExtras(bundle);
            startActivity(intent);

        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        getSupportLoaderManager().destroyLoader(QRCodeAsync.ASYNC_ID);
        if (inviteFriendDialog != null) {
            inviteFriendDialog.dismiss();
        }
        if (showQRCodeDialog != null) {
            showQRCodeDialog.recycle();
            showQRCodeDialog.dismiss();
            showQRCodeDialog = null;
        }
        UMShareAPI.get(this).release();
        if (QRCodeBitmap != null) {
            QRCodeBitmap.recycle();
        }

        super.onDestroy();
    }
}
